'use client';

import React, { useRef } from 'react';
import { nextImage, prevImage } from './ui/swiper-img';
import Image from 'next/image';
import RegisterSwiper from '@/components/swiper/register-swiper';

interface Props {
  value: {
    src: string;
    alt?: string;
    title?: string;
  }[];
  width: number;
  height: number;
  loop?: boolean;
  autoplay?: boolean;
  autoplayDelay?: number;
  showNavigation?: boolean;
}

const Swiper: React.FC<Props> = ({
  value,
  width,
  height,
  loop = true,
  autoplay = true,
  autoplayDelay = 1500,
  showNavigation = true,
}) => {
  const swiperElRef = useRef<any>(null);
  const timer = useRef<number | null>(null);
  const navigate = (direction: 'prev' | 'next') => {
    if (swiperElRef.current) {
      swiperElRef.current.autoplay = false;
      if (direction === 'prev') {
        swiperElRef.current.swiper.slidePrev();
      } else if (direction === 'next') {
        swiperElRef.current.swiper.slideNext();
      }
      if (autoplay) {
        timer.current && clearInterval(timer.current);
        timer.current = window.setTimeout(() => {
          swiperElRef.current.autoplay = true;
          swiperElRef.current.autoplayDelay = autoplayDelay;
        }, 3000);
      }
    }
  };

  return (
    <>
      <RegisterSwiper />
      <div className="relative w-full h-full">
        {showNavigation && (
          <>
            <div
              className="absolute top-1/2 -translate-y-1/2 left-[10px] w-9 h-9 bg-no-repeat bg-center cursor-pointer z-[5]"
              title="previous"
              onClick={() => void navigate('prev')}
              style={{
                backgroundImage: prevImage,
              }}
            ></div>
            <div
              className="absolute top-1/2 -translate-y-1/2 right-[10px] w-9 h-9  bg-no-repeat bg-center cursor-pointer z-[5]"
              title="next"
              onClick={() => void navigate('next')}
              style={{
                backgroundImage: nextImage,
              }}
            ></div>
          </>
        )}

        <swiper-container
          className="relative h-full w-full"
          ref={swiperElRef}
          loop={loop ? 'true' : 'false'}
          autoplay={autoplay ? 'true' : 'false'}
          autoplay-delay={autoplayDelay.toString()}
        >
          {value.map((img, index) => (
            <swiper-slide key={index}>
              <div className="w-full relative">
                <Image
                  title={img.title}
                  src={img.src}
                  alt={img.alt ?? ''}
                  width={width}
                  height={height}
                  priority
                  style={{
                    objectFit: 'contain',
                  }}
                ></Image>
              </div>
            </swiper-slide>
          ))}
        </swiper-container>
      </div>
    </>
  );
};

export default Swiper;
